package com.yc.thread.basic;
import java.time.LocalDateTime;

/**
 * 实现Runnable接口
 * Runnable:可运行的任务
 * @author zwei
 * @create 2024-07-14 9:34
 */
public class Test2_Runnable {
    public static void main(String[] args) {
        //创定一个线程  绑定任务
        Runnable task=new ShowTimeTask();
        Thread t=new Thread(task);
        t.start();


        Runnable task2=new ShowTimeTaskInner();
        Thread t2=new Thread(task2);
        t2.start();

        //匿名内部类写法：
        Thread t3=new Thread(new Runnable() {
            private boolean flag;
            @Override
            public void run() {
                LocalDateTime d = LocalDateTime.now();
                while (!flag) {
                    System.out.println(Thread.currentThread().getName() + "输出当前时间：" + d);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        });
        t3.start();

        //语法四：因为Runnable接口上有@FunctionalInterface  表示这个接口是正常lambda语法
        Thread t4=new Thread(    ()->  {
            LocalDateTime d = LocalDateTime.now();
            while (true) {
                System.out.println(Thread.currentThread().getName() + "输出当前时间：" + d);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t4.start();
    }
    //内部类写法
    static class ShowTimeTaskInner implements Runnable{
        private boolean flag;
        @Override
        public void run() {
            LocalDateTime d = LocalDateTime.now();
            while (!flag) {
                System.out.println(Thread.currentThread().getName() + "输出当前时间：" + d);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
//外部类写法
class ShowTimeTask implements Runnable {
    private boolean flag;

    @Override
    public void run() {
        LocalDateTime d = LocalDateTime.now();
        while (!flag) {
            System.out.println(Thread.currentThread().getName() + "输出当前时间：" + d);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
